<template>
  <div class="app-container">
    <el-card class="box-card" shadow="always" v-show="showSearch">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px" @submit.native.prevent>
        <el-form-item label="客户名称" prop="supplierName">
          <el-input @change="searchChange" v-model="searchInput" placeholder="请输入客户名称/联系人手机" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="queryParams.contacts" placeholder="请输入联系人" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="协助人" prop="assistUserId">
          <!-- <el-input v-model="queryParams.assistUserName" placeholder="请输入联系人" clearable
                        @keyup.enter="handleQuery" /> -->
          <el-select
            v-model="queryParams.assistUserId"
            filterable
            clearable
            remote
            reserve-keyword
            placeholder="请选择协助人"
            @keyup.enter="handleQuery"
          >
            <el-option v-for="item in assistList" :key="item.userId" :label="item.realityName" :value="item.userId + ''"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户经理" prop="operationManager">
          <!-- <el-input v-model="queryParams.operationManager" placeholder="请输入联系人" clearable
                        @keyup.enter="handleQuery" /> -->
          <el-select
            v-model="queryParams.operationManager"
            filterable
            clearable
            remote
            reserve-keyword
            placeholder="请选择客户经理"
            @keyup.enter="handleQuery"
          >
            <el-option v-for="item in assistList" :key="item.userId" :label="item.realityName" :value="item.userId"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售区域" prop="saleAreaName">
          <el-input v-model="queryParams.saleAreaName" placeholder="请输入销售区域" clearable @keyup.enter="handleQuery" />
          <!-- <el-select v-model="queryParams.operationManagerName" filterable clearable remote reserve-keyword
                        placeholder="请选择销售区域" @keyup.enter="handleQuery">
                        <el-option v-for="item in areaList" :key="item.id" :label="item.areaName" :value="item.id">
                        </el-option> 
                        </el-option>
                    </el-select> -->
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div :gutter="20" class="content mt20">
      <div v-show="tableHeight && showTree" :span="edgeSize" :offset="0" :style="`height: ${tableHeight}px;position: relative;background-color:#fff`">
        <div class="left" :style="`height: ${tableHeight}px;`">
          <div class="left-top">
            <div class="">客户分类</div>
            <div class="">
              <img style="width: 30px; height: 30px" @click="handleEdge" :src="showTree ? imgs[1] : imgs[0]" />
            </div>
          </div>
          <el-tree
            ref="classifyTreeRef"
            class="mt-2"
            node-key="id"
            :data="classifyList"
            :current-node-key="currentItem"
            :props="{ label: 'label', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            highlight-current
            default-expand-all
            @node-click="itemClick"
          />
          <div class="buttons">
            <div class="button" @click="handleAddClassify">
              <el-icon>
                <CirclePlus />
              </el-icon>
              <div>新增分类</div>
            </div>
            <div class="button" @click="handleEditClassify">
              <el-icon>
                <Edit />
              </el-icon>
              <div>编辑分类</div>
            </div>
            <div class="button" @click="handleDelClassify">
              <el-icon>
                <Delete />
              </el-icon>
              <div>删除分类</div>
            </div>
          </div>
        </div>
      </div>
      <el-card ref="table" shadow="always" :class="{ 'w-tree': showTree, 'w-all': !showTree }">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" @click="handleAdd">添加客户 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">删除 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" @click="handleMyAssist">需我协助 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" @click="handleMyCustomer">我的客户 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" @click="handleImport"
              ><el-icon><UploadFilled /></el-icon>导入</el-button
            >
          </el-col>

          <right-toolbar :v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table
          :height="'calc(100vh - 422px)'"
          v-loading="loading"
          :data="dataSource"
          @selection-change="handleSelectionChange"
          @row-dblclick="dbclick"
        >
          <el-table-column type="selection" width="55" align="center" :selectable="selectHandle" />
          <!-- <el-table-column label="客户编号" align="left" prop="supplierCode" width="150" /> -->
          <el-table-column label="客户名称" align="left" prop="supplierName" width="250" />
          <el-table-column label="分类" align="left" prop="supplierClassifyName" width="150" />
          <el-table-column label="协助人" align="left" prop="assistUserName" width="150" />
          <el-table-column label="客户经理" align="left" prop="operationManagerName" width="150" />
          <el-table-column label="销售区域" align="left" prop="saleAreaName" width="200" />

          <el-table-column label="级别价" align="left" prop="classStatus">
            <template #default="scope">
              {{ selectDictLabel(price_level, scope.row.priceType) }}
            </template>
          </el-table-column>
          <el-table-column label="联系人" align="left" prop="contactName" width="200">
            <template #default="scope">
              <div class="contactName">{{  scope.row.contactName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="left" prop="createTime" width="200" />
          <el-table-column label="操作" align="left" width="120" fixed="right">
            <template #default="scope">
              <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
              <el-divider direction="vertical"></el-divider>
              <el-button type="text" @click="handleDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="total" v-model:page.sync="queryParams.pageNum" v-model:limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-card>
    </div>

    <div class="fixed-icon" @click="handleEdge" v-show="!showTree">
      <el-icon>
        <DArrowRight />
      </el-icon>
    </div>
    <addForm ref="modelForm" :classifyList="classifyList" @ok="getList"></addForm>
    <cusClassifyAddForm ref="cusClassifyAddForm" @ok="getClassifyTree('1', setCurrentKey)"></cusClassifyAddForm>
    <importForm ref="importForm" @ok="getList"></importForm>
  </div>
</template>

<script>
import addForm from './modules/addForm.vue';
import importForm from './modules/importForm.vue';
import useUserStore from '@/store/modules/user';
import cusClassifyAddForm from '../cusClassify/modules/addForm.vue';
import listMixin from '@/mixins/listMixin';
import request from '@/utils/request';
import { getUserNotPermission } from '@/api/system/user';
import zk from '@/assets/images/zhankai.svg';
import zd from '@/assets/images/zhedie.svg';
import { handleTree, findNodeInTree } from '@/utils/ruoyi';
const userStore = useUserStore();
export default {
  name: 'customer',
  components: {
    addForm,
    importForm,
    cusClassifyAddForm
  },
  mixins: [listMixin],
  data() {
    return {
      queryParams: {
        type: '1',
        pageNum: 1,
        pageSize: 10
      },
      urls: {
        list: '/order/supplier/list',
        delete: '/order/supplier'
      },
      dataSource: [],

      currentIndex: 0,
      price_level: [],
      counting_method: [],
      tableHeight: 0,
      imgs: [zk, zd],
      assistList: [],
      currentItem: {},
      showTree: true,
      searchInput:null,
    };
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.tableHeight = this.$refs.table.$el.scrollHeight;
      }, 200);
    });
    // 获取分类列表
    this.getUserAllList();
    this.getClassifyTree('1');
    this.getDicts(['price_level', 'counting_method']);
    this.getArea();
  },
  methods: {
    searchChange(v){
      // 如果是手机号
      const reg = /^1[3-9][0-9]\d{8}$/;
      if(reg.test(v)){
        this.queryParams.contactPhone = v
        this.queryParams.supplierName = ''
      }else{
        this.queryParams.supplierName = v
        this.queryParams.contactPhone = ''
      }
    
    },
    setCurrentKey(res) {
      this.$nextTick(() => {
        if (findNodeInTree(this.classifyList[0], this.currentItem.id)) {
          this.$refs.classifyTreeRef.setCurrentKey(this.currentItem.id);
        } else {
          this.$refs.classifyTreeRef.setCurrentKey(null);
          this.itemClick({});
        }
      });
    },
    listAfter() {
      this.$nextTick(() => {
        this.tableHeight = this.$refs.table.$el.scrollHeight;
      });
    },
    itemClick(data) {
      this.currentItem = data;
      console.log(this.currentItem, '666');
      this.queryParams.supplierClassifyId = data.id;
      this.getList();
    },
    handleAdd() {
      this.$refs.modelForm.add({ supplierClassifyId: this.queryParams.supplierClassifyId });
    },
    handleAddClassify() {
      this.$refs.cusClassifyAddForm.add({});
    },
    handleEditClassify() {
      console.log(this.currentItem, 'this.currentItem');
      if (!this.currentItem || !this.currentItem.id) {
        this.$message.warning('请选择分类');
        return;
      }
      this.$refs.cusClassifyAddForm.edit(this.currentItem.id);
    },
    handleMyCustomer() {
      this.queryParams.defaultAssistFlag = true;
      this.queryParams.assistUserId = '';
      this.handleQuery();
    },
    handleImport() {
      this.$refs.importForm.show({});
    },
    handleMyAssist() {
      this.queryParams.defaultAssistFlag = false;
      this.queryParams.assistUserId = userStore.userId;
      this.handleQuery();
    },
    handleDelClassify() {
      if (!this.currentItem) {
        this.$message.warning('请选择分类');
        return;
      }
      this.$modal
        .confirm('确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          request({
            url: '/order/supplierClassify/' + this.currentItem.id,
            method: 'delete'
          }).then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess('删除成功');
              this.currentItem = {};
              this.getClassifyTree('1', this.setCurrentKey);
            } else {
              this.$modal.msgError(res.msg);
            }
          });
        })
        .catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        type: '1',
        pageNum: 1,
        pageSize: 10
      };
      this.currentItem = {};
      this.$refs.classifyTreeRef.setCurrentKey(null);
      this.getList();
    },
    handleEdge() {
      this.showTree = !this.showTree;
      this.$nextTick(() => {
        setTimeout(() => {
          this.tableHeight = this.$refs.table.$el.scrollHeight;
        }, 200);
      });
    },
    // 获取后台用户
    getUserAllList() {
      getUserNotPermission()
        .then((res) => {
          this.assistList = res;
        })
        .catch((err) => {
          console.log(err);
        });
    }
  }
};
</script>

<style scoped lang="scss">
.tree-item {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  /* border-bottom: 1px solid #777; */
  /* padding: 5px 0; */
  cursor: pointer;
  background-color: #fff;
}

.tree-icon {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.item__selected {
  background-color: #e6f7ff;
}

.tree__line {
  width: 24px;
  height: 24px;
  border-bottom: 1px dashed #e5e5eb;
  border-left: 1px dashed #e5e5eb;
}

.tree__title {
  padding: 0 4px;
  margin-bottom: -24px;
}

.left {
  width: 240px;
  // height: calc(100vh - 234px);
  border: 1px solid #e6ebf5;
  // position: relative;
  border-radius: 4px;
  overflow-x: hidden;
  overflow-y: auto;
  padding-bottom: 60px;

  .fodder_list {
    z-index: 20;

    .fodder_item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 20px;
      cursor: pointer;

      .box {
        display: flex;
        justify-content: flex-start;
        align-items: center;

        svg {
          margin-right: 10px;
        }

        .fodder_name {
          font-size: 14px;
          color: #303133;
          width: 84px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    .fodder_item.active,
    .fodder_item:hover {
      background-color: #f5f5f5;
    }
  }

  .buttons {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    position: absolute;
    bottom: 1px;
    width: 238px;
    border-top: 1px solid #e6ebf5;
    background-color: #fff;
    z-index: 21;
    font-size: 12px;
    color: #303133;

    .button {
      cursor: pointer;
      padding: 10px;
      text-align: center;

      i {
        margin-right: 5px;
      }
    }

    .button:not(:last-child) {
      border-right: 1px solid #e6ebf5;
    }

    .button:hover {
      color: #409eff;
    }
  }
}

.main {
  height: calc(100vh - 240px);
  overflow-x: scroll;

  .title {
    font-size: 12px;
    color: #606266;
    width: 100px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}

.left-top {
  display: flex;
  justify-content: space-between;
  padding: 6px 20px;
  border-bottom: 1px solid #e6ebf5;
  align-items: center;

  .box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-size: 24px;
    color: #303133;
    font-weight: bold;
  }
}

.fixed-icon {
  position: fixed;
  //left: 0;
  top: 400px;
  z-index: 999;
  background-color: #409eff;
  padding: 12px 2px;
  color: #fff;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  display: flex;
  cursor: pointer;
}

.content {
  display: flex;
  justify-content: space-between;
  position: relative;
}

.w-tree {
  width: calc(100% - 260px);
}

.w-all {
  width: 100%;
}
.contactName{
  width:200px;
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
}
</style>